import json
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Config:
    def __init__(self, filepath):
        self.filepath = filepath
        self.config_data = self.load_config()
        self.dict2attr(self.config_data)
    def load_config(self):
        with open(self.filepath, 'r', encoding='utf-8') as f:
            return json.load(f)

    def reload_config(self):
        self.config_data = self.load_config()
        # print(f"Configuration reloaded: {self.config_data}")
        self.dict2attr(self.config_data)
    def get(self, key, default=None):
        return self.config_data.get(key, default)
    def dict2attr(self,dic):
        for k, v in dic.items():
            if isinstance(v, dict):
                # print(v)
                v = self.dict2attr(v)
            # print(v)
            setattr(self, k, v)
        return self

class ConfigChangeHandler(FileSystemEventHandler):
    def __init__(self, config):
        self.config = config

    def on_modified(self, event):
        print(f"Detected change in: {event.src_path}")
        print(f"Watching file: {self.config.filepath}, event path: {event.src_path}")
        if  self.config.filepath in event.src_path:
            print("Reloading configuration...")
            self.config.reload_config()

def main():
    config = Config('config.json')
    event_handler = ConfigChangeHandler(config)
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=False)
    observer.start()
    try:
        while True:
            time.sleep(1)
            print(f"Current config: {config.version},  {config.num}，{config.debug}")
            config.num += 1
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == '__main__':
    main()